package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AddFriendEntity;
import com.sam.im.heiqun.entities.AddFriendResultEntivity;
import com.sam.im.heiqun.entities.CircleNums;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.entities.SearchUserEntity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.VersionEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.service.IMIntentService;
import com.sam.im.heiqun.sound.ChatCallActivity;
import com.sam.im.heiqun.sound.entity.ConstantApp;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.FixedSpeedScroller;
import com.sam.im.heiqun.uis.adapters.FragmentAdapter;
import com.sam.im.heiqun.uis.fragments.FindFragment;
import com.sam.im.heiqun.uis.fragments.FriendFragment;
import com.sam.im.heiqun.uis.fragments.GroupFragment;
import com.sam.im.heiqun.uis.fragments.MessageFragment;
import com.sam.im.heiqun.uis.fragments.SetTwoFragment;
import com.sam.im.heiqun.utils.BadgeTool;
import com.sam.im.heiqun.utils.ConversationUtils;
import com.sam.im.heiqun.utils.EventBusTypeData;
import com.sam.im.heiqun.utils.EventBusTypeObject;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.NetworkConnectChangedReceiver;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.ToastUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseActivity;
import com.yuyh.library.utils.DownUtils;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.view.progress.SVProgressHUD;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;

/**
 * 主页
 */

public class MainActivity extends BaseActivity implements AMapLocationListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    @BindView(R.id.message_layout)
    RelativeLayout messageLayout;
    @BindView(R.id.friend_layout)
    RelativeLayout friendLayout;
    @BindView(R.id.message)
    TextView message;
    @BindView(R.id.friend)
    TextView friend;
    @BindView(R.id.group)
    TextView group;
    @BindView(R.id.find)
    TextView find;
    @BindView(R.id.set)
    TextView set;
    @BindView(R.id.message_num)
    TextView message_num;
    @BindView(R.id.friend_num)
    TextView friend_num;
    @BindView(R.id.group_num)
    TextView group_num;
    @BindView(R.id.main_layout)
    RelativeLayout mainLayout;
    @BindView(R.id.id_viewpager)
    ViewPager idViewpager;
    @BindView(R.id.plus_search)
    ImageView plusSearch;
    @BindView(R.id.rich_scan)
    ImageView rich_scan;
    @BindView(R.id.plus_add)
    ImageView plusAdd;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.mes_jiazai)
    ImageView mejiazai;
    @BindView(R.id.net_state)
    TextView netState;
    @BindView(R.id.find_num)
    TextView find_num;
    @BindView(R.id.find_layout)
    RelativeLayout find_layout;
    @BindView(R.id.group_layout)
    RelativeLayout group_layout;
    @BindView(R.id.set_layout)
    RelativeLayout set_layout;
    @BindView(R.id.find_news)
    TextView findnews;
    @BindView(R.id.group_news)
    TextView groupnews;
    private App mApp;
    private PGService mPgService = PGService.getInstance();
    // public static MainActivity mainActivity;
    private OkHttpClient mOkHttpClient;
    private AlertDialog updateDialog;
    private FragmentAdapter mAdapter;
    private List<Fragment> fragments = new ArrayList<Fragment>();
    // 初始化定时器
    Timer timer = new Timer();
    private int currentG = 0;
    private PopupMenu popupMenu;
    private Menu menu;
    private int richScanCode = 1;
    private int tagint = -1;
    private Animation an;
    private static int START_LOCATION = 999;
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            // 需要做的事:发送消息
            Message message = new Message();
            message.what = START_LOCATION;
            myhandler.sendMessage(message);
        }
    };
    private Handler myhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 3: {//更新软件
                    final VersionEntivity versionEntivity = (VersionEntivity) msg.obj;
                    if (versionEntivity == null) {
                        return;
                    }
                    showUpdateDialog(versionEntivity);
                    break;
                }
                case 4: {//更新软件下载进度
                    if (!msg.obj.equals("1")) {
                        SVProgressHUD.getProgressBar(MainActivity.this).setProgress(msg.arg1);
                        SVProgressHUD.setText(MainActivity.this, "进度 " + Float.parseFloat(msg.obj.toString()) + "%");
                    } else {
                        SVProgressHUD.dismiss(MainActivity.this);
                        SVProgressHUD.getProgressBar(MainActivity.this).setProgress(0);
                        File file = new File(Constant.APK_URL, Constant.APP_NAME);
                        if (file != null) {
                            Intent intent = new Intent();
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setAction(android.content.Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(file),
                                    "application/vnd.android.package-archive");
                            startActivity(intent);
                        }
                    }
                    break;
                }
                case 999://定位
                    mlocationClient.startLocation();
                    break;
            }
        }
    };
    private UserEntivity userEntivity;
    private FindFragment e;

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer refresh) {
        if (refresh == EventBusType.REFRESH_BASE_ACTIVITY) {
            recreate();
        }
    }

    Intent payintent;
    JSONObject jsonObject = null;
    private ConversationUtils conversationUtils;
    private String friend_id;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(EventBusTypeData event) {
        if (event != null) {
            switch (event.getType()) {
                case Constant.TOMessageTypeVoiceRequest:
                    Log.i("fanhui", "ChatCallActivity.isActive:" + ChatCallActivity.isActive);
                    if (ChatCallActivity.isActive) {
                        //向你发起音频  视频通话
                        payintent = new Intent(MainActivity.this, CallFriendThreeActivity.class);
                        payintent.putExtra("data", event.getMsg());
                        startActivity(payintent);
                    } else {

                        if (ToolsUtils.isConversation) {
                            if (event.getMsg() != null && !event.getMsg().equals("")) {
                                //正在和别人通话
                                conversationUtils = new ConversationUtils(this);
                                try {
                                    jsonObject = new JSONObject(event.getMsg());
                                    friend_id = jsonObject.getInt("fromId") + "";
                                    if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                                        //拒接接受语音
                                        acceptCall(Constant.TOMessageTypeRefuseVoiceRequest, Integer.parseInt(friend_id));
                                    } else {
                                        acceptCall(Constant.TOMessageTypeRefuseVideoRequest, Integer.parseInt(friend_id));
                                    }
                                    MsgEntity msgEntity = new MsgEntity();
                                    msgEntity.setMsgString(getResources().getString(R.string.chat_friend_no));
                                    String msg = new Gson().toJson(msgEntity);
                                    conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, Integer.parseInt(friend_id));
                                } catch (JSONException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        } else {
                            //向你发起音频  视频通话
                            payintent = new Intent(MainActivity.this, CallFriendAgreeActivity.class);
                            payintent.putExtra("data", event.getMsg());
                            startActivity(payintent);
                        }
                    }
                    break;

                case Constant.TOMessageTypeAgreeVoiceRequest:
                    //同意音频通话
                    EventBus.getDefault().post(Constant.TOMessageTypeRefuseVideoRequest);
                    try {
                        JSONObject jsonObject = new JSONObject(event.getMsg());
                        Intent intent = new Intent(getApplicationContext(), ChatCallActivity.class);
                        intent.putExtra(ConstantApp.ACTION_KEY_CHANNEL_NAME, jsonObject.getString("content"));
                        intent.putExtra("fromid", jsonObject.getInt("fromId"));
                        intent.putExtra("type", jsonObject.getInt("messageType"));
                        startActivity(intent);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case Constant.TOVIDEOTHREECALLEXIT:
                    //挂断通知
                    Log.i("fanhui", "ChatCallActivity.isActive:" + ChatCallActivity.isActive);
                    if (ChatCallActivity.isActive) {
                        //三方邀请
                        EventBus.getDefault().post(new EventBusTypeData(Constant.TOVIDEOTHREECALL, event.getMsg()));
                    } else {
                        EventBus.getDefault().post(Constant.TOMessageTypeRefuseVideoRequest);
                    }
                    break;
                case EventBusType.GROUP_APPLY_GRPOUP_REFRENSH_N:
                    showToast(event.getMsg());
                    break;
                case EventBusType.GROUP_APPLY_GRPOUP_REFRENSH_Y:
                    String groupid = event.getMsg();
                    if (null != groupid && !TextUtils.isEmpty(groupid)) {
                        getGroupById(groupid);
                    }
                    break;
            }
        }

    }

    /**
     * 拒绝同意拒绝音频
     *
     * @param type
     */
    public void acceptCall(int type, int fid) {
        try {
            conversationUtils.sendMsg(jsonObject.getString("content"), type, fid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void init(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        mPgService = PGService.getInstance();
        mApp = App.getInstance();
        mOkHttpClient = new OkHttpClient();
        userEntivity = ToolsUtils.getUser();
        tagint = getIntent().getIntExtra("int", -1);
        //  GlideCatchUtil.getInstance().clearCacheDiskSelf();
        //  DataCleanManager.cleanExternalCache(this);
        //完成了所有的数据更新在刷新界面
        //    getGroupMembers();
        //获取版本
        getVersion(false);
        initFragment();
        //startIntentService();
        IntentFilter filter = new IntentFilter();
        NetworkConnectChangedReceiver networkConnectChangedReceiver = new NetworkConnectChangedReceiver();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        filter.addAction("android.net.wifi.STATE_CHANGE");
        //registerReceiver(networkConnectChangedReceiver,filter);
        TimingGetGroupMembers();
        initMenu();

        if (tagint == 1) {
            idViewpager.setCurrentItem(0);
        }
        getlocation();
        timer.schedule(task, 1000, 1200000); // 1s后执行task,经过1s再次执行
        List<CircleNums> circleNumses = CircleNums.find(CircleNums.class, "unicid=? and isread=? and type!=?", new String[]{ToolsUtils.getMyUserId(), "0", Constant.MESSAGE_TYPR_CIRCLE + ""});
        List<CircleNums> circleNumses2 = CircleNums.find(CircleNums.class, "unicid=? and isread=? and type=?", new String[]{ToolsUtils.getMyUserId(), "0", Constant.MESSAGE_TYPR_CIRCLE + ""});
        if (circleNumses != null && circleNumses.size() != 0) {
            find_num.setText(circleNumses.size() + "");
            find_num.setVisibility(View.VISIBLE);
            findnews.setVisibility(View.GONE);
        } else if (circleNumses2.size() > 0) {
            find_num.setVisibility(View.GONE);
            findnews.setVisibility(View.VISIBLE);
        } else {
            find_num.setVisibility(View.GONE);
            findnews.setVisibility(View.GONE);
        }
    }

    public void startIntentService() { // 创建需要启动的
        Intent intent = new Intent(this, IMIntentService.class);
        startService(intent);
    }

    public void initMenu() {

        popupMenu = new PopupMenu(this, plusAdd);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu, menu);

        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {

                    case R.id.add_contacts://添加联系人
                    {
                        startActivity(PhoneConstantActivity.class);
                        break;
                    }
                    case R.id.create_group: {//创建群
                        startActivity(SelecteGroupFriendActivity.class);
                        break;
                    }
                    case R.id.search_group: {//搜索群
                        startActivity(SeachGroupActivity.class);
                        break;
                    }
                    case R.id.scan: {//扫描
                        startActivityForResult(CommonScanActivity.class, richScanCode);
                        break;
                    }

                    default:
                        break;
                }
                return false;
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setcirclenums(String s) {
        if (s.equals("动态已读")) {
            find_num.setVisibility(View.GONE);
            e.setCircleNum(0, 2);
        } else if (s.equals("朋友动态已读")) {
            findnews.setVisibility(View.GONE);
            e.setCircleNum(0, 1);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //这里显示最后一次
    public void getcircleNums(CircleNums s) {
        if (s != null) {
            List<CircleNums> circleNumses = CircleNums.find(CircleNums.class, "unicid=? and isread=? and type!=?", new String[]{ToolsUtils.getMyUserId(), "0", Constant.MESSAGE_TYPR_CIRCLE + ""});
            if (circleNumses != null && circleNumses.size() != 0) {
                find_num.setText(circleNumses.size() + "");
                find_num.setVisibility(View.VISIBLE);
                findnews.setVisibility(View.GONE);
                e.setCircleNum(circleNumses.size(), 2);
            } else {
                e.setCircleNum(1, 1);
                find_num.setVisibility(View.GONE);
                findnews.setVisibility(View.VISIBLE);
            }
        }
    }

    /**/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void netState(String state) {
        if (state.equals(Constant.NET)) {//有网络，需要重新连接
            netState.setVisibility(View.GONE);
        } else if (state.equals(Constant.NOT_NET)) {//没有网络
            netState.setVisibility(View.VISIBLE);
        } else if (state.equals(Constant.NOT_NET_SERVICE) && null != mejiazai) {
            an = AnimationUtils.loadAnimation(this,
                    R.anim.update_loading_progressbar_anim);
            LinearInterpolator lin = new LinearInterpolator();
            an.setInterpolator(lin);
            an.setRepeatCount(-1);
            mejiazai.setBackgroundResource(R.drawable.loading);
            mejiazai.startAnimation(an);
            mejiazai.setVisibility(View.VISIBLE);
            an.startNow();
            title.setText(getResources().getString(R.string.now_lianjie));
        } else if (state.equals(Constant.FRAGMENT_HIND_TITLE) && null != mejiazai) {

            if (null != an) {
                an.cancel();
            }
            title.setText(R.string.message);
            mejiazai.setBackground(null);
            mejiazai.setVisibility(View.GONE);
        }
    }

    /**
     * 定时获取列表
     */
    private void TimingGetGroupMembers() {
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                getGroupMembers();
            }
        }, 1800000, 1800000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        startIntentService();
    }

    /**
     * 设置滚动速度
     */
    private void setViewPagerScrollSpeed() {
        try {
            Field mScroller = null;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(idViewpager.getContext());
            mScroller.set(idViewpager, scroller);
        } catch (NoSuchFieldException e) {

        } catch (IllegalArgumentException e) {

        } catch (IllegalAccessException e) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showNum(Integer code) {
        if (code == Constant.MAIN_BOTTOM_TIP_NUM) {
            showActivityMsgNum();
        } else if (code == Constant.MAIN_ACTIVITY_TO_LOGIN) {
            //不要修改此处，服务器正在调试
            //  showToast("账户从其它地方登陆！");
            //  doExit();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showNum(EventBusTypeObject code) {
        if (null != code) {
            if (code.getType() == EventBusType.SHOW_MAIN_TOAST) {
                ToastUtil.showtoast(MainActivity.this, code.getSessiontype());
            }
        }
    }

    /**
     * 做 退出登录 操作
     */
    /*private void doExit() {
        new PrefsUtils(this, Constant.MOBILE).put(Constant.MOBILE, "");
        new PrefsUtils(this, Constant.PWD).put(Constant.MOBILE, "");
        startActivity(LoginActivity.class);
        mApp.getSocket().disconnect();
        App.socket = null;
        fragments.clear();
        finish();
    }*/

    /**
     * 显示消息提示数字
     */
    public void showActivityMsgNum() {
        int num = 0;
        List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=?", new String[]{ToolsUtils.getMyUserId() + ""});
        if (null != messageEntivities && messageEntivities.size() > 0) {
            int size = messageEntivities.size();
            for (int i = 0; i < size; i++) {
                MessageEntivity entivity = messageEntivities.get(i);
                Log.i("-----", "showActivityMsgNum: -------" + new Gson().toJson(entivity));
                Log.i("-----", "showActivityMsgNum: ===========entivity.getNick()=" + entivity.getNick() + "==========entivity.getMessageNum()=" + entivity.getMessageNum());
                if (entivity.getType() == 15) {
                    continue;
                }
                num = num + Integer.parseInt("" + entivity.getMessageNum());
            }
        }
        if (0 == num) {
            message_num.setVisibility(View.GONE);
            boolean success = BadgeTool.showCount(MainActivity.this, 0, 0);
        } else {
            message_num.setVisibility(View.VISIBLE);
            message_num.setText(num > 99 ? "99+" : "" + num);

//            boolean success = ShortcutBadger.applyCount(MainActivity.this, num);
            boolean success = BadgeTool.showCount(MainActivity.this, num, 0);

        }
    }

    /**
     * 显示消息提示数字
     */
    public void showActivityMsgNum(int num) {
        if (0 == num) {
            message_num.setVisibility(View.GONE);
        } else {
            message_num.setVisibility(View.VISIBLE);
            message_num.setText(num > 99 ? "99+" : "" + num);
        }
    }


    /**
     * 功能：Fragment页面改变事件
     */
    public class TabOnPageChangeListener implements ViewPager.OnPageChangeListener {

        //当滑动状态改变时调用
        public void onPageScrollStateChanged(int state) {

        }

        //当前页面被滑动时调用
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        //当新的页面被选中时调用
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    title.setText(getResources().getString(R.string.message));
                    switchToCurrent(R.id.message);
                    break;
                case 1:


                    switchToCurrent(R.id.friend);
                    break;
                case 2:


                    switchToCurrent(R.id.group);
                    break;
                case 3:
                    title.setText(getResources().getString(R.string.find));
                    switchToCurrent(R.id.find_layout);
                    break;
                case 4:
                    title.setText(getResources().getString(R.string.set));
                    switchToCurrent(R.id.set_layout);
                    break;
            }
        }
    }

    /**
     * 更新新好友个数
     */
    public void showActivityFrdNum() {
        int num = 0;
        List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "type=? or type=?", new String[]{Constant.MESSAGE_TYPR_APPLY_FRIEND + "", Constant.MESSAGE_TYPR_APPLE_GROUP + ""});
        if (null != messageEntivities && messageEntivities.size() > 0) {
            for (int i = 0; i < messageEntivities.size(); i++) {
                num = num + Integer.parseInt("" + messageEntivities.get(i).getMessageNum());
            }
        }
        if (0 == num) {
            friend_num.setVisibility(View.GONE);
        } else {
            friend_num.setVisibility(View.VISIBLE);
            friend_num.setText(num > 99 ? "99+" : "" + num);
        }
    }

    public void getGroupMembers() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String userId = ToolsUtils.getMyUserId();
                List<ImGroupEntivity> groupsInfo = ImGroupEntivity.find(ImGroupEntivity.class, "currentid = ?", userId);
//                for (int i = 0; i < groupsInfo.size(); i++) {
                if (currentG < groupsInfo.size()) {
                    getGroupMember(groupsInfo.get(currentG).getId(), userId);
                    currentG++;
                } else {
                    currentG = 0;
                }
//                }
            }
        }).start();
    }

    /**
     * 获取版本
     */
    public void getVersion(final boolean isHand) {
        mPgService.getVersion().subscribe(new AbsAPICallback<VersionEntivity>() {
            @Override
            public void onNext(VersionEntivity versionEntivity) {//成功后连接长连接
                String current = ToolsUtils.getVersion(MainActivity.this);
                String ss = versionEntivity.getVersions();
                if (!current.equals(ss)) {
                    Message message = new Message();
                    message.what = 3;
                    message.obj = versionEntivity;
                    myhandler.sendMessage(message);
                } else {
                    if (isHand) {
                        showToast("已是最新版本");
                    }
                }
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("info", "版本获取失败" + ex.getCode() + ex.getDisplayMessage());
            }
        });
    }

    private void initFragment() {
        fragments.add(new MessageFragment());
        fragments.add(new FriendFragment());
        fragments.add(new GroupFragment());
        e = new FindFragment();
        fragments.add(e);
        fragments.add(new SetTwoFragment());
        /**
         * 初始化Adapter
         */
        mAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments);
        setViewPagerScrollSpeed();
        idViewpager.setAdapter(mAdapter);
        idViewpager.setOffscreenPageLimit(5);
        idViewpager.addOnPageChangeListener(new TabOnPageChangeListener());
        switchToCurrent(R.id.message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addFriend(ImMessage imMessage) {
        if (imMessage.getFromType() == Constant.FROM_TYPE_SYS && (imMessage.getMessageType() == Constant.MESSAGE_TYPR_APPLE_ADD_FRIEND_AGREE)) {//申请加好友通过
            getUserById(imMessage.getDestid() + "", 10);//10表示添加新的好友
        }
        if (imMessage.getFromType() == Constant.FROM_TYPE_SYS && (
                imMessage.getMessageType() == Constant.MESSAGE_TYPR_FRIEND_ADD)) {//申请加好友通过
            getUserById(imMessage.getDestid() + "", 11);//11表示默认添加新的好友
        }
        if (imMessage.getFromType() == Constant.FROM_TYPE_SYS && imMessage.getMessageType() == Constant.MESSAGE_TYPR_INVITE_GROUP) {//被邀请加入群
            getGroupById(imMessage.getFromid() + "");
        }
        if (imMessage.getMessageType() == Constant.MESSAGE_TYPE_BE_JOIN_GROUP) {//被邀请加群
            getGroupById(imMessage.getFromid() + "");
        }
        if (imMessage.getFromType() == Constant.FROM_TYPE_SYS && imMessage.getMessageType() == Constant.MESSAGE_TYPR_GROUP_CHANGE) {//群昵称修改
            UserEntivity userEntivity = ToolsUtils.getUser();
            getGroupByid(imMessage.getFromid() + "", userEntivity.getId());
        }
    }

    public void switchToCurrent(int id) {
        message.setTextColor(getResources().getColor(R.color.black_secondary));
        friend.setTextColor(getResources().getColor(R.color.black_secondary));
        group.setTextColor(getResources().getColor(R.color.black_secondary));
        find.setTextColor(getResources().getColor(R.color.black_secondary));
        set.setTextColor(getResources().getColor(R.color.black_secondary));
        message.setCompoundDrawables(null, getSwitchDrawable(R.drawable.message), null, null);
        friend.setCompoundDrawables(null, getSwitchDrawable(R.drawable.friend), null, null);
        group.setCompoundDrawables(null, getSwitchDrawable(R.drawable.group_tab_no), null, null);
        find.setCompoundDrawables(null, getSwitchDrawable(R.drawable.circle_nomal), null, null);
        set.setCompoundDrawables(null, getSwitchDrawable(R.drawable.setting), null, null);
        switch (id) {
            case R.id.message: {
                title.setText(getResources().getString(R.string.message));
                message.setTextColor(getResources().getColor(R.color.colorAccent));
                message.setCompoundDrawables(null, getSwitchDrawable(R.drawable.message_rest), null, null);
                break;
            }
            case R.id.friend: {
                List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid=? and is_black=?", ToolsUtils.getMyUserId(), "0");
                if (null != imFriendEntivities) {
                    title.setText(getResources().getString(R.string.friend_num) + imFriendEntivities.size() + "）");
                } else {
                    title.setText(getResources().getString(R.string.friend_num) + "0）");
                }
//                title.setText("好友");
                friend.setTextColor(getResources().getColor(R.color.colorAccent));
                friend.setCompoundDrawables(null, getSwitchDrawable(R.drawable.friend_rest), null, null);
                break;
            }
            case R.id.group: {
//                List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid=? and is_black=?", ToolsUtils.getMyUserId(), "0");
                List<ImGroupEntivity> mGroupEntivities = ImGroupEntivity.find(ImGroupEntivity.class, "currentid = ?", ToolsUtils.getMyUserId());
                if (null != mGroupEntivities) {
                    title.setText(getResources().getString(R.string.group) + "(" + mGroupEntivities.size() + "）");
                } else {
                    title.setText(getResources().getString(R.string.group) + "(" + "0）");
                }
                group.setTextColor(getResources().getColor(R.color.colorAccent));
                group.setCompoundDrawables(null, getSwitchDrawable(R.drawable.group_rest), null, null);
                break;
            }
            case R.id.find_layout: {
                title.setText(getResources().getString(R.string.find));
                find.setTextColor(getResources().getColor(R.color.colorAccent));
                find.setCompoundDrawables(null, getSwitchDrawable(R.drawable.circle_chose), null, null);
                break;
            }
            case R.id.set_layout: {
                title.setText(getResources().getString(R.string.set));
                set.setTextColor(getResources().getColor(R.color.colorAccent));
                set.setCompoundDrawables(null, getSwitchDrawable(R.drawable.setting_set), null, null);
                break;
            }
        }
    }

    /**
     * 根据群id 查找群信息
     *
     * @param groupid
     * @param fromid
     */
    public void getGroupByid(final String groupid, final long fromid) {
       /* if (groupEntivity != null) {
            Log.i("info","groupentivity=="+groupEntivity.toString());
            groupEntivity.setCurrentid(fromid);
            groupEntivity.setReceiveTip(1);
            groupEntivity.save();
            EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
        }else {
            Log.i("info","groupentivity==空的");
        }*/
        mPgService.getGroupById(groupid, fromid + "").subscribe(new AbsAPICallback<ImGroupEntivity>() {
            @Override
            public void onNext(ImGroupEntivity groupEntivity) {
                ImGroupEntivity groupEntivitys = ImGroupEntivity.findById(ImGroupEntivity.class, Long.parseLong(groupid));
                if (groupEntivitys != null) {
                    groupEntivitys.setCurrentid(fromid);
                    Integer receiveTip = groupEntivitys.getReceiveTip();
                    if (receiveTip != null) {
                        groupEntivitys.setReceiveTip(receiveTip);
                    } else {
                        groupEntivitys.setReceiveTip(1);
                    }
                    groupEntivitys.setName(groupEntivity.getName());
                    groupEntivitys.save();
                }
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
            }

            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.please_import_right_phone_and_psd));
            }
        });
    }

    @OnClick({R.id.message_layout, R.id.friend_layout, R.id.find_layout, R.id.set_layout, R.id.plus_add, R.id.plus_search, R.id.group})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.message_layout: {
                idViewpager.setCurrentItem(0);
                break;
            }
            case R.id.friend_layout: {

                idViewpager.setCurrentItem(1);
                break;
            }
            case R.id.group: {

                idViewpager.setCurrentItem(2);

                break;
            }
            case R.id.find_layout: {
                idViewpager.setCurrentItem(3);
                break;
            }
            case R.id.set_layout: {
                idViewpager.setCurrentItem(4);
                break;
            }
            case R.id.plus_add: {
                popupMenu.show();
                break;
            }
            case R.id.plus_search: {//搜索好友
                startActivity(SelecteLocalFriendActivity.class);
                break;
            }
        }
    }

    private Drawable getSwitchDrawable(final int mipmapId) {
        Drawable img_off;
        img_off = getResources().getDrawable(mipmapId);
        img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
        return img_off;
    }

    @Override
    public void onResume() {
        boolean islogining = ToolsUtils.saveLoginstate(this, false, 2);
        if (App.socket == null || !App.socket.connected() && islogining) {
            String savesocketstr = ToolsUtils.savesocketstr(this, "", "", 2);
            String[] split = savesocketstr.split("___");
            App.initSocket(split[0], split[1]);
        } else {
            Log.i("info", "socket==" + App.socket);
        }
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    SharedPreferences sp;

    @Override
    protected void onDestroy() {
        sp = getSharedPreferences("call_video", Context.MODE_PRIVATE);
        String friend_id = sp.getString("call_friend", null);
        if (friend_id != null && !"".equals(friend_id)) {
            ConversationUtils conversationUtils = new ConversationUtils(this);

            MsgEntity msgEntity = new MsgEntity();
            msgEntity.setMsgString(getString(R.string.chat_time) + ChatCallActivity.getTime(ChatCallActivity.recLen));
            String msg = new Gson().toJson(msgEntity);
            conversationUtils.sendMsg(msg, Constant.TOMessageTypeCancleVoiceVideo, Integer.parseInt(friend_id));
            conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, Integer.parseInt(friend_id));
        }
        sp = getSharedPreferences("call_video", Context.MODE_PRIVATE);
        sp.edit().putString("call_friend", "").commit();
        ChatActivity.isLive = false;
        ChatCallActivity.recLen = 0;
        EventBus.getDefault().unregister(this);
        timer.cancel();
        fragments.clear();
        super.onDestroy();
    }

    /**
     * 扫描二维码添加好友，id前面附带 a_ 或者 b_
     *
     * @param str
     */
    private void requestFriend(String str) {

        String typeStr = str.substring(0, 1);
        final String type;

        if (typeStr.equals("a")) {
            type = "1";
        } else {
            type = "2";
        }

        final String destid = str.substring(2);

        String fromid = ToolsUtils.getMyUserId();
        mPgService.getNetApi()
                .requestFriend(type, destid, fromid, null)
                .compose(RxJavaUtil.<AddFriendEntity>applySchedules())
                .subscribe(new AbsAPICallback<AddFriendEntity>() {
                    @Override
                    public void onNext(AddFriendEntity s) {
                        if ("2".equals(type)) {
                            getGroupById(destid);
                        } else {
                            showToast(getResources().getString(R.string.friend_apply_already_commit));
                        }
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        try {
                            AddFriendResultEntivity resultModel = new Gson().fromJson(ex.getDisplayMessage(), AddFriendResultEntivity.class);
                            if ("2".equals(resultModel.getCode())) {
                                getUserById(destid);
                            }
                        } catch (Exception e) {
                            showToast(getResources().getString(R.string.friend_apply_already_commitno));
                        }
                    }
                });
    }

    private void getUserById(String destid) {
        String fromid = ToolsUtils.getMyUserId();
        mPgService.getUserById(fromid, destid).subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity mFriendEntivity) {
                mFriendEntivity.setCurrentid(ToolsUtils.getUser().getId());
                mFriendEntivity.setIsBlack("0");
                mFriendEntivity.save();
                //刷新好友页面数据
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    //获取群信息
    private void getGroupById(final String groupId) {
        String fromid = ToolsUtils.getMyUserId();
        mPgService.getGroupById(groupId, fromid).subscribe(new AbsAPICallback<ImGroupEntivity>() {
            @Override
            public void onNext(ImGroupEntivity groupEntivity) {
                groupEntivity.setCurrentid(Long.valueOf(ToolsUtils.getMyUserId()));
                groupEntivity.setReceiveTip(1);
                groupEntivity.save();
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    //获取好友信息
    private void getUserById(String destid, final int type) {
        String fromid = ToolsUtils.getMyUserId();
        mPgService.getUserById(fromid, destid).subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity friendEntivity) {
                if (type == 10)//新增好友
                {
                    if (!ToolsUtils.isMyFriendForId(friendEntivity.getId())) {

                        UserEntivity userEntivity = ToolsUtils.getUser();
                        //更新数据库
                        friendEntivity.setCurrentid(userEntivity.getId());
                        friendEntivity.setIsBlack("0");
                        friendEntivity.save();
                        //刷新好友页面数据
                        EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                        showToast(friendEntivity.getNickName() + getString(R.string.agree_your_friend_apply));

                        //手动创建一个文本消息
                        ImMessage localImMessage = new ImMessage();
                        localImMessage.setFromid(friendEntivity.getCurrentid());
                        localImMessage.setFromname(friendEntivity.getName());
                        localImMessage.setImageIconUrl(friendEntivity.getHeadUrl());
                        localImMessage.setDestid(friendEntivity.getId());
                        localImMessage.setFromType(1);
                        localImMessage.setVersion(1);
                        localImMessage.setSendTime(System.currentTimeMillis());
                        localImMessage.setReceiveTime(localImMessage.getSendTime());
                        localImMessage.setDevType(1);
                        localImMessage.setMessageType(Constant.MESSAGE_TYPR_BQEMOJI);
                        localImMessage.setType(ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT);
                        localImMessage.setMsgId(String.valueOf(System.currentTimeMillis()));
                        localImMessage.setContent(String.format("{\"msgString\":\"%s\"}", "我通过了你的朋友验证请求。现在我们可以开始聊天了"));
                        localImMessage.setUniqueness(localImMessage.getFromid() + "_" + localImMessage.getDestid());
                        EventBus.getDefault().post(localImMessage);

                        MessageEntivity messageEntivity = IMMessageToJson.ImMessageToMessageEntivity(localImMessage, Constant.FROM_TYPE_OTHER);
                        localImMessage.save();//存储接受的数据
                        if (messageEntivity != null) {
                            EventBus.getDefault().post(messageEntivity);
                        } else {
                            EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                        }

                    }
                } else if (type == 11) {
                    if (!ToolsUtils.isMyFriendForId(friendEntivity.getId())) {
                        UserEntivity userEntivity = ToolsUtils.getUser();
                        //更新数据库
                        friendEntivity.setCurrentid(userEntivity.getId());
                        friendEntivity.setIsBlack("0");
                        friendEntivity.save();
                        //刷新好友页面数据
                        EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                    }
                }
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Constant.REQUEST_SCAN_MODE_BARCODE_MODE) {
            //String money = data.getStringExtra("money");
            String str = data.getStringExtra("destid");
            Log.i("info", "str==" + str);
            String destid = str.substring(2);
            String typeStr = str.substring(0, 1);
            if (typeStr.equals("a")) {
                Bundle bundle = new Bundle();
                bundle.putLong("id", Long.parseLong(destid));
                bundle.putInt("type", 0);
                startActivity(FriendDetailActivity.class, bundle);
            } else if (typeStr.equals("b")) {
                String fromid = ToolsUtils.getMyUserId();
                showProgress(getResources().getString(R.string.now_down));
                mPgService.getGroupById(destid, fromid).subscribe(new AbsAPICallback<ImGroupEntivity>() {
                    @Override
                    public void onNext(ImGroupEntivity groupEntivity) {
                        hideProgress();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("groupSeri", groupEntivity);
                        bundle.putLong("groupid", groupEntivity.getId());
                        startActivity(GroupDetailsActivity.class, bundle);
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        hideProgress();
                        ToolsUtils.showToast(MainActivity.this, getResources().getString(R.string.net_error));
                    }
                });

            } else if (typeStr.equals("c")) {
                Intent payintent = new Intent(MainActivity.this, PayActivity.class);
                payintent.putExtra("money", destid);
                startActivity(payintent);
            } else if (typeStr.equals("d")) {
                Intent payintent = new Intent(MainActivity.this, PayActivity.class);
                payintent.putExtra("paymoney", destid);
                startActivity(payintent);
            } else if (str.contains("http")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(str);
                intent.setData(content_url);
                startActivity(intent);
            } else {
                showToast(getResources().getString(R.string.no_konw_qrcode));
            }

        } else if (requestCode == Constant.MESSAGE_MAIN_GO_GROUP_RESULT && resultCode == Constant.MESSAGE_MAIN_GO_GROUP_RESULT) {
            switchToCurrent(R.id.find_layout);
        }
    }

    /**
     * 弹出 升级询问 Dialog
     */
    private void showUpdateDialog(final VersionEntivity versionEntivity) {

        View layout = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_version_updata, null);
        TextView updateCancel = (TextView) layout.findViewById(R.id.update_cancel);
        TextView updateCommit = (TextView) layout.findViewById(R.id.update_commit);
        TextView versionTextView = (TextView) layout.findViewById(R.id.version);
        View partition = layout.findViewById(R.id.partition);
        versionTextView.setText(getResources().getString(R.string.have_usable_new_vsesion_V) + versionEntivity.getVersions());

        // updateCancel.setVisibility(View.GONE);
        partition.setVisibility(View.GONE);
        updateCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });
        updateCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
                SVProgressHUD.showWithProgress(MainActivity.this, "进度 " + 0 + "%", SVProgressHUD.SVProgressHUDMaskType.Black);
                //核查版本更新
                DownUtils.downApk(mOkHttpClient, versionEntivity.getUrl(), Constant.APP_NAME, myhandler, MainActivity.this);
            }
        });
        updateDialog = new android.support.v7.app.AlertDialog.Builder(MainActivity.this).setView(layout).create();
        updateDialog.setCancelable(false);
        updateDialog.show();
        WindowManager.LayoutParams attributes = updateDialog.getWindow().getAttributes();
        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        attributes.width = ((int) (defaultDisplay.getWidth() * 0.85));
        updateDialog.getWindow().setAttributes(attributes);
    }


    /**
     * 查询群组好友列表
     */
    private void getGroupMember(final long groupId, String fromid) {
        mPgService.getGroupMember(groupId + "", fromid).subscribe(new AbsAPICallback<SearchUserEntity>() {
            @Override
            public void onNext(final SearchUserEntity friendEntivity) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<ImFriendEntivity> mFriendEntivities = friendEntivity.getInfo();
                        ToolsUtils.saveGroupUserS(mFriendEntivities, groupId);
                    }
                }).start();

            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {//what the fuck  退出时主动断开链接？？？
        if (keyCode == KeyEvent.KEYCODE_BACK) {//如果返回键按下
            //此处写退向后台的处理
            moveTaskToBack(false);
           /* Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            if (App.socket != null) {
                App.socket.close();
                App.socket = null;
            }*/
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
            moveTaskToBack(false);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                Log.i("info", "定位成功==" + amapLocation.getLatitude() + "  " + amapLocation.getLongitude());
                mlocationClient.stopLocation();
                HashMap<String, String> map = new HashMap<>();
                map.put("lat", amapLocation.getLatitude() + "");
                map.put("lnt", amapLocation.getLongitude() + "");
                ToolsUtils.saveSf(MainActivity.this, map);
                mPgService.uplocation(amapLocation.getLatitude() + "", amapLocation.getLongitude() + "", ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                    @Override
                    protected void onResultError(ApiException ex) {

                    }

                    @Override
                    public void onNext(ValidateEntivity validateEntivity) {
                        if (validateEntivity != null) {
                            Log.i("info", "位置提交成功==" + validateEntivity.getInfo());
                        }
                    }
                });
            } else {
                mlocationClient.stopLocation();
                // mlocationClient.startLocation();
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    public AMapLocationClientOption mLocationOption = null;
    public AMapLocationClient mlocationClient = null;

    //定位
    public void getlocation() {

        //声明mLocationOption对象
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        // mlocationClient.startLocation();
    }
   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//如果返回键按下
            //此处写退向后台的处理
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }*/
}
